package com.longrise.android.byjk.plugins.course.coursedetail;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.course.coursedetail.videoexercises.VideoExercisesActvity;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.model.CourseTrainDirBean;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CacheTask;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance.InsuranceActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * Created by godliness on 2017/7/19.
 * 课程详情课：负责课程相关状态展示
 * CourseFragment 负责ExpandableListView所有操作的管理
 * this activity launch mode is singleTask
 * V1.3.7开始使用
 */

public class CourseDetailActivity2 extends BaseActivity<CoursePresenter>
        implements CourseDetailContract.CourseView, View.OnClickListener {

    public static final String TAG = "CourseDetailActivity2";

    public static final String INTENT_EXTRA_PARAMS = "courseid";
    public static final String COURSE_PRICE = "course_price";

    /**
     * 课程id
     */
    private String mCourseId;

    /**
     * top view
     */
    private ImageView mIvTopView;
    private ImageView mIvPlayView;
    private TextView mTvDate;
    private View mBack;
    private View mConment;

    /**
     * 培训证书,培训记录表
     */
    private Button mTvCert;
    private Button mTvList;

    /**
     * 已关闭,已下架
     */
    private Button mTvCourseTotalState;

    /**
     * 立即开通/立即购买,免费延期
     */

    private Button mTvDelay;

    private View mLoadView;
    private TextView mTvtitle;
    private TextView mTvteacherName;
    private TextView mTvgrade;
    private TextView mTvintrodetail;
    private Button mBtbuy;
    private TextView mTvbuy;
    private RelativeLayout mRLbuy;
    private String mPrice;
    private Button mBtstudy;
    private CourseTrainDirBean.Result mResultBean;
    private Button mBtkt;
    private TextView mTvkhcsTitle;
    private TextView mTvkhcstg;
    private RelativeLayout mRlkhcs;
    private RelativeLayout mRlkhcstips;
    private LinearLayout mLLcontent;

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            onRestoreState(state);
        } else {
            getExtraData();
        }
        return R.layout.activity_coursedetail2;
    }


    private void getExtraData() {
        Intent extraIntent = getIntent();
        mCourseId = extraIntent.getStringExtra(INTENT_EXTRA_PARAMS);
        mPrice = extraIntent.getStringExtra(COURSE_PRICE);
    }

    @Override
    public void initView() {
        initTopView();
        initContentView();
        initBottomView();
        regEvent(true);
        EventBus.getDefault().register(this);
        mPresenter.initData(mCourseId);
    }

    private void initContentView() {
        mLoadView = findViewById(R.id.rela_load_xqpc);
        mTvtitle = (TextView) findViewById(R.id.coursedetail_title);
        mTvteacherName = (TextView) findViewById(R.id.coursedetail_teacher);
        mTvgrade = (TextView) findViewById(R.id.coursedetail_grade);
        mTvintrodetail = (TextView) findViewById(R.id.coursedetail_introduce_detail);
        mTvkhcsTitle = (TextView) findViewById(R.id.coursedetail_khcs_tv_title);
        mTvkhcstg = (TextView) findViewById(R.id.coursedetail_khcs_tv);
        mRlkhcstips = (RelativeLayout) findViewById(R.id.coursedetail_khcs_tips);
        mRlkhcs = (RelativeLayout) findViewById(R.id.coursedetail_khcs_rl);
        mLLcontent = (LinearLayout) findViewById(R.id.coursedetail_content_ll);
    }

    private void initTopView() {
        mIvTopView = (ImageView) findViewById(R.id.iv_topview);
        autoChangeTopViewSize(mIvTopView);
        mIvPlayView = (ImageView) findViewById(R.id.iv_play);
        mTvDate = (TextView) findViewById(R.id.tv_date);
        mBack = findViewById(R.id.viewback);
        mConment = findViewById(R.id.viewcoment);
    }

    private void autoChangeTopViewSize(ImageView view) {
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();
        int width = AppUtil.getScreenWidth();
        lp.height = width / 2;
        view.setLayoutParams(lp);
        view.requestLayout();
    }

    private void regEvent(boolean isClick) {
        if (mBack != null) {
            mBack.setOnClickListener(isClick ? this : null);
        }
        if (mConment != null) {
            mConment.setOnClickListener(isClick ? this : null);
        }
        if (mIvPlayView != null) {
            mIvPlayView.setOnClickListener(isClick ? this : null);
        }
        if (mTvCert != null) {
            mTvCert.setOnClickListener(isClick ? this : null);
        }
        if (mTvList != null) {
            mTvList.setOnClickListener(isClick ? this : null);
        }
        if (mTvCourseTotalState != null) {
            mTvCourseTotalState.setOnClickListener(isClick ? this : null);
        }
        if (mBtbuy != null) {
            mBtbuy.setOnClickListener(isClick ? this : null);
        }
        if (mTvDelay != null) {
            mTvDelay.setOnClickListener(isClick ? this : null);
        }
        if (mBtstudy != null) {
            mBtstudy.setOnClickListener(isClick ? this : null);
        }
        mBtkt.setOnClickListener(this);
        mRlkhcs.setOnClickListener(this);
    }

    private void initBottomView() {
        mTvCert = (Button) findViewById(R.id.tv_cert);
        mTvList = (Button) findViewById(R.id.tv_list);
        mTvCourseTotalState = (Button) findViewById(R.id.tv_total_state);
        mBtbuy = (Button) findViewById(R.id.course_buy_bt);
        mTvbuy = (TextView) findViewById(R.id.course_buy_tv);
        mRLbuy = (RelativeLayout) findViewById(R.id.course_buy_rl);
        mTvDelay = (Button) findViewById(R.id.tv_delay);
        mBtstudy = (Button) findViewById(R.id.coursedetail_study);
        mBtkt = (Button) findViewById(R.id.coursedetail_kt);
    }

    @Override
    public void showLoadingDialog() {
        if (mLoadView != null) {
            mLoadView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void dismissLoadingDialog() {
        if (mLoadView != null) {
            mLoadView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onError(String msg) {
        if (mLoadView != null) {
            mLoadView.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(msg)) {
            showToast(msg);
        }
    }

    /**
     * 表示数据加载完成
     */
    @Override
    public void showMsg(CourseTrainDirBean.Result resultBean) {
        this.mResultBean = resultBean;
        mIvPlayView.setVisibility(View.VISIBLE);
        mLLcontent.setVisibility(View.VISIBLE);

        String title = resultBean.name;  //标题
        String teacherName = resultBean.teachername; //老师
        String grade = resultBean.avgscore; //评分
        String introduceDetail = resultBean.infosummary;//课程内容介绍
        boolean isfinish = resultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).isfinish;//课后练习题和视频是否都完成
        boolean videopass = resultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).videopass;//视频是否播放完成
        boolean qapass = resultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).qapass; //课后练习题是否通过


        mTvtitle.setText(title);
        if (TextUtils.isEmpty(teacherName)) {
            mTvteacherName.setText("讲师：");
        } else {
            mTvteacherName.setText(Html.fromHtml("讲师：<font color='#333333'>" + teacherName + "</font>"));
        }
        mTvgrade.setText(Html.fromHtml("评分：<font color='#333333'>" + grade + "分</font>"));
        mTvintrodetail.setText(introduceDetail);

        //课后测试的标题
        mTvkhcsTitle.setText(title + "测试题");
        if (isfinish) { //全部通过
            mTvkhcstg.setText("已通过");
            mTvkhcstg.setTextColor(Color.parseColor("#D8D8D8"));
            mRlkhcstips.setVisibility(View.GONE);
        } else {
            mTvkhcstg.setText("未通过");
            mTvkhcstg.setTextColor(Color.parseColor("#FBA140"));
            if (videopass) {//视频通过后 隐藏提示
                mRlkhcstips.setVisibility(View.GONE);
            } else {
                mRlkhcstips.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * @param cert      培训证书
     * @param recordTab 记录表
     */
    @Override
    public void setCertInfor(boolean cert, boolean recordTab) {
        PrintLog.e(TAG, "cert: " + cert + "  recordTab: " + recordTab);
        if (mTvCert != null) {
            mTvCert.setVisibility(cert ? View.VISIBLE : View.GONE);
        }
        if (mTvList != null) {
            mTvList.setVisibility(recordTab ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 设置购买信息
     *
     * @param buy        是否需要购买
     * @param buyText    购买按钮的text
     * @param delay      是否可以延期
     * @param totalState 课程总状态
     * @param stateText  课程总状态text
     */
    @Override
    public void setBuyInfor(boolean buy, String buyText, boolean delay, boolean totalState, String stateText) {
        PrintLog.e(TAG, "buy: " + buy + "  buyText: " + buyText + "  delay: " + delay + "  totalState: " + totalState + "  stateText: " + stateText);
        if (mTvCourseTotalState != null) {
            mTvCourseTotalState.setVisibility(totalState ? View.VISIBLE : View.GONE);
            mTvCourseTotalState.setText(stateText);
        }
        if (mRLbuy != null) {
            if ("0.00".equals(mPrice)) {
                mRLbuy.setVisibility(View.GONE);
                mBtkt.setVisibility(buy ? View.VISIBLE : View.GONE);
            } else {
                mRLbuy.setVisibility(buy ? View.VISIBLE : View.GONE);
                mBtbuy.setText(buyText);
                mTvbuy.setText("¥" + mPrice);
            }
        }
        if (mTvDelay != null) {
            mTvDelay.setVisibility(delay ? View.VISIBLE : View.GONE);
        }
        //立即学习按钮
        if (!buy && !delay && !totalState) {
            mBtstudy.setVisibility(View.VISIBLE);
            mRlkhcs.setClickable(true); //课后练习题可以点击
        } else {
            mBtstudy.setVisibility(View.GONE);
            mRlkhcs.setClickable(false); //课后练习题不可以点击
        }

    }

    /**
     * 设置课后练习题的按钮是否可以点击
     */
    public void setKhcsClickable(boolean clickable) {
        mRlkhcs.setClickable(clickable);
    }

    @Override
    public String getCourseId() {
        return mCourseId;
    }

    @Override
    public void loadCoursePic(String picUrl) {
        if (mIvTopView != null && !isFinishing()) {
            Glide.with(this)
                    .load(picUrl)
                    .error(AppUtil.getResources().getDrawable(R.drawable.img03))
                    .into(mIvTopView);
        }
    }


    /**
     * 延期成功 最新版本该功能已取消
     */
    @Override
    public void showDelaySuccessDialog() {

    }

    /**
     * 评论按钮的显示状态
     */
    @Override
    public void setCommentVisiableState(boolean commentVisiableState) {
        if (mConment != null) {
            mConment.setVisibility(commentVisiableState ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void setExpiretime(String date) {
        if (mTvDate != null && !TextUtils.isEmpty(date)) {
            mTvDate.setText(String.format(getString(R.string.availability), date));
        }
    }

    @Override
    public void setEnable(boolean enable) {
        if (mBtbuy != null) {
            mBtbuy.setClickable(enable);
        }
    }

    /**
     * 跳转到课后练习题
     */
    @Override
    public void jumpToExercises() {
        VideoParams videoParams = getVideoParams();
        if (videoParams == null) {
            return;
        }
        Intent intent = new Intent(mContext, VideoExercisesActvity.class);
        intent.putExtra(VideoExercisesActvity.COURSEBEAN, videoParams);
        mContext.startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(INTENT_EXTRA_PARAMS, mCourseId);
    }

    private void onRestoreState(Bundle state) {
        mCourseId = state.getString(INTENT_EXTRA_PARAMS);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.viewback:
                onBack();
                break;

            case R.id.viewcoment:
                //评分
                mPresenter.toScoreActivity(this);
                break;

            case R.id.iv_play:
                //第一个未通过的课件
                toStudy();
                break;

            case R.id.tv_cert:
                //培训证书
                mPresenter.toCertActivity();
                break;

            case R.id.tv_list:
                //培训记录表
                mPresenter.toRecordActivity();
                break;

            case R.id.tv_total_state:

                break;

            case R.id.course_buy_bt: //立即购买
                //购买
                mPresenter.toBuyCourse();
                break;

            case R.id.tv_delay:
                //延期，V1.3.7延期功能取消。
                mPresenter.toDelayCourse();
                break;

            case R.id.coursedetail_study: //立即学习
                toStudy();
                break;

            case R.id.coursedetail_kt: //立即开通
                mPresenter.toBuyCourse();
                break;

            case R.id.coursedetail_khcs_rl: //课后练习题item 点击
                mPresenter.clickKhlxt();
                break;

            default:
                break;
        }
    }


    /**
     * 立即学习
     */
    private void toStudy() {
        if (mResultBean == null) {
            return;
        }
        if (!mResultBean.isablestudy) { //该课程不能学习的情况下
            mPresenter.dispatchStudyMsg();
            return;
        }
        VideoParams videoParams = getVideoParams();
        Intent intent = new Intent(mContext, InsuranceActivity.class);
        intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
        startActivity(intent);
    }


    /**
     * 组装视频参数
     *
     * @return videoParams
     */
    private VideoParams getVideoParams() {
        if (mResultBean == null) {
            return null;
        }
        String courseid = mResultBean.courseid;
        String studentno = mResultBean.studentno;
        String cwid = mResultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).cwid;
        String pathno = mResultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).pathno;
        String cwidName = mResultBean.traindirstruct.dirinfo.get(0).nextnodeinfo.get(0).name;
        VideoParams videoParams = new VideoParams();
        videoParams.mCourseId = courseid;
        videoParams.mStudentNo = studentno;
        videoParams.mCwid = cwid;
        videoParams.mPathNo = pathno;
        videoParams.mCwidName = cwidName;
        return videoParams;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerEventBus(CourseDetailEvent event) {
        if (event == null) {
            return;
        }
        if (event.isUpdateCoursePraxis() || event.isRefreshDetail() || event.isRefreshScore() || event.getCoursePosition() != null) {
            mPresenter.refreshData();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void onBack() {
        finish();
    }

    private void release() {
        regEvent(false);
        mPresenter.setFinished();
        CacheTask.shutdownTask();
        //注意卸载
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
    }

}
